package com.kede.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.kede.domain.ResourceAreaMap;
import com.kede.repository.ResourceAreaMapRepository;
import com.kede.rest.po.ResourceAreaMapPo;
import com.kede.service.ResourceAreaMapService;
import com.kede.service.dto.ResourceAreaMapDto;
import com.kede.service.dto.ResourceAreaMapQueryCriteria;
import com.kede.service.mapstruct.ResourceAreaMapMapper;
import com.kede.utils.FileUtil;
import com.kede.utils.PageUtil;
import com.kede.utils.QueryHelp;
import com.kede.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @description 服务实现
* @author Pr.li
* @date 2023-04-22
**/
@Service
@RequiredArgsConstructor
public class ResourceAreaMapServiceImpl implements ResourceAreaMapService {

    private final ResourceAreaMapRepository resourceAreaMapRepository;
    private final ResourceAreaMapMapper resourceAreaMapMapper;

    @Override
    public Map<String,Object> queryAll(ResourceAreaMapQueryCriteria criteria, Pageable pageable){
        Page<ResourceAreaMap> page = resourceAreaMapRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(resourceAreaMapMapper::toDto));
    }

    @Override
    public List<ResourceAreaMapDto> queryAll(ResourceAreaMapQueryCriteria criteria){
        return resourceAreaMapMapper.toDto(resourceAreaMapRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ResourceAreaMapDto findById(Integer areaId) {
        ResourceAreaMap resourceAreaMap = resourceAreaMapRepository.findById(areaId).orElseGet(ResourceAreaMap::new);
        ValidationUtil.isNull(resourceAreaMap.getAreaId(),"ResourceAreaMap","areaId",areaId);
        return resourceAreaMapMapper.toDto(resourceAreaMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResourceAreaMapDto create(ResourceAreaMap resources) {
        return resourceAreaMapMapper.toDto(resourceAreaMapRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ResourceAreaMap resources) {
        ResourceAreaMap resourceAreaMap = resourceAreaMapRepository.findById(resources.getAreaId()).orElseGet(ResourceAreaMap::new);
        ValidationUtil.isNull( resourceAreaMap.getAreaId(),"ResourceAreaMap","id",resources.getAreaId());
        resourceAreaMap.copy(resources);
        resourceAreaMapRepository.save(resourceAreaMap);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer areaId : ids) {
            resourceAreaMapRepository.deleteById(areaId);
        }
    }

    @Override
    public void download(List<ResourceAreaMapDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ResourceAreaMapDto resourceAreaMap : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setResourceAreaMap(List<Integer> areaValues, List<Integer> resourceIds) {
        List<ResourceAreaMap> arrayList = new ArrayList<>();
        //每次给resource绑定的地区就是最新的数据 所以要删除这个资源之前的关系数据
//        resourceAreaMapRepository.deleteByResourceIdIn(resourceIds);
        //然后新增
        for (Integer areaValue: areaValues){
            for (Integer resourceId: resourceIds){
                arrayList.add( new ResourceAreaMap(resourceId,areaValue));
            }
        }
        resourceAreaMapRepository.saveAllAndFlush(arrayList);
    }

    /**
     * 根据地区查这个地区下资源id
     *
     * @Author: Pr.li
     * @Date: 2023/4/22 15:40
     * @Param: []
     * @Return: java.util.List<java.lang.Integer>
     ***/
    @Override
    public List<Integer> getResourceIdsByAreaIds(List<Integer> areaIds){
        return resourceAreaMapRepository.findResourceIdsByAreaIds(areaIds);
    }

    /**
     * 根据资源查相关的地区
     *
     * @Author: Pr.li
     * @Date: 2023/4/22 15:40
     * @Param: []
     * @Return: java.util.List<java.lang.Integer>
     ***/
    @Override
    public List<Integer> getAreaIdsByResourceIds(List<Integer> resourceIds){
        //默认是 0  即为全国
        List<Integer> list = new ArrayList<>(Arrays.asList(0));
        if (CollectionUtil.isEmpty(resourceIds)){
            return new ArrayList<>();
        }
        for (Integer resourceId : resourceIds) {
            List<Integer> areaIdsByResourceIds = resourceAreaMapRepository.findAreaIdsByResourceIds(resourceId);
            if (CollectionUtil.isEmpty(areaIdsByResourceIds)) {
                list = new ArrayList<>();
                return list;
            }
            if(areaIdsByResourceIds.get(0).equals(0)){
                continue;
            }
            if (list.get(0).equals(0)){
                // 将第一个不为0 的列表赋值给list
                    list = areaIdsByResourceIds;
                //如果不是全国就取交集
            }else{
                list = (List<Integer>) CollectionUtils.intersection(list, areaIdsByResourceIds);
            }

        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelAreadIdsAndResourceIds(ResourceAreaMapPo resourceAreaMapPo) {
        for (Integer areaValue : resourceAreaMapPo.getAreaValues()) {
            for (Integer resourceId : resourceAreaMapPo.getResourceIds()) {
                resourceAreaMapRepository.deleteResourceIdAndAreaId(areaValue,resourceId);
            }
        }
    }


}